//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package 力扣.题库.二分查找.demo_2080;

import java.util.Arrays;

public class RangeFreqQuery {
    private int[] arr;

    public RangeFreqQuery(int[] arr) {
        this.arr = arr;
    }

    public int query(int left, int right, int value) {
        int[] temp = Arrays.copyOfRange(this.arr, left, right + 1);
        int n = temp.length;
        Arrays.sort(temp);
        if (value >= temp[0] && value <= temp[n - 1]) {
            if (value == temp[0] && value == temp[n - 1]) {
                return n;
            } else {
                int l = -1;
                int r = n;

                while(l + 1 < r) {
                    int mid = l + (r - l) / 2;
                    if (value < temp[mid]) {
                        r = mid;
                    } else {
                        l = mid;
                    }
                }

                int count;
                for(count = 0; l > 0 && temp[l] == value; --l) {
                    ++count;
                }

                return count;
            }
        } else {
            return 0;
        }
    }
}
